﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using System.IO;

namespace GT.Xna.Windows
{
    public static partial class GameExtensions
    {
        public static Texture2D GetTexture(this System.Drawing.Image image)
        {
            Texture2D texture = null;
            GraphicsDevice graphics = GameGlobals.Game.GraphicsDevice;

            if (image == null)
                return null;


            if (texture == null || texture.IsDisposed || texture.Width != image.Width || texture.Height != image.Height || texture.Format != SurfaceFormat.Color)
            {
                if (texture != null && !texture.IsDisposed)
                    texture.Dispose();

                texture = new Texture2D(graphics, image.Width, image.Height, false, SurfaceFormat.Color);
            }
            else
            {
                for (int i = 0; i < 16; i++)
                {
                    if (graphics.Textures[i] == texture)
                    {
                        graphics.Textures[i] = null;
                        break;
                    }
                }
            }

            // Memory stream to store the bitmap data.
            using (MemoryStream ms = new MemoryStream())
            {
                // Save to that memory stream.
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                // Go to the beginning of the memory stream.
                ms.Seek(0, SeekOrigin.Begin);

                // Fill the texture.
                texture = Texture2D.FromStream(graphics, ms, image.Width, image.Height, false);
            }
            return texture;
        }
    }
}
